<template>
  <div class="add-order">
    <el-dialog v-model="showDialog" :title="`商家配置`" width="800px" :before-close="cancel">
      <el-form v-loading="loading" :model="ruleForm.form" ref="ruleFormRef" :rules="rules" label-width="135px">
        <el-form-item prop="configId" label="供应商配置">
          <el-select v-model="ruleForm.form.configId" placeholder="请选择供应商">
            <el-option
              v-for="item in payConfigList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model.trim="ruleForm.form.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="是否启用" prop="status">
          <el-switch
              v-model="ruleForm.form.status"
              :active-value="1"
              :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
                <span class="dialog-footer">
                    <el-button @click="cancel">取消</el-button>
                    <el-button type="primary" @click="submitForm(ruleFormRef)" :loading="loading">确定</el-button>
                </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {
  getOneStoreConfig,
  saveOrUpdateStore
} from "@/api/product";
import {
  getStoreInfos,
} from "@/api/system";
import type {FormInstance, FormRules} from 'element-plus'
import sysConfigApi from "@/api/sysConfigApi";
const props = defineProps({
  showDialog: Boolean,
  modelData: {
    type: Object,
    default: {},
  },
});
const Store = useStore();
const {modelData, showDialog} = toRefs(props)
const loading = ref(false)
const ruleFormRef = ref<FormInstance>()
const storeList = ref([])
const payConfigList = ref([] as any)
const ruleForm = reactive({
  form: {
    id: "",
    storeName: modelData.value.storeName,
    storeUserId: modelData.value.id,
    merchantId: Store.state.user.merchantId,
    configId: "",
    status: 0,
    phone: '',
  },
})
const rules = reactive({
  configId: [
    {
      required: true,
      message: "请选择供应商",
      trigger: "blur",
    },
  ],
  phone: [
    {
      required: true,
      message: '请输入手机号',
      trigger: 'blur',
    }
  ],
  status: [
    {
      required: true,
      message: "请选择是否启用",
      trigger: "blur",
    },
  ],
});
watch(
    () => showDialog.value,
    async (showDialog) => {
      if (showDialog) {
        loading.value = true
        // await getStoreList();
        await getStoreConfigs();
        loading.value = false
      }
    }
)

const submitForm = async (formEl: FormInstance | undefined) => {
  console.log('[ formEl ]', formEl)
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      addSaveOrUpdateStore()
    } else {
      console.log('error submit!', fields)
    }
  })
}


// 商家配置信息
const getStoreConfigs = async () => {
  let params = {
    id: modelData.value.id
  }
  getConfigList()
  const rs: any = await getOneStoreConfig(params);
  if (rs.code == 200) {
    ruleForm.form = {
      id: rs.payload.id,
      storeName: modelData.value.storeName,
      storeUserId: modelData.value.id,
      merchantId: Store.state.user.merchantId,
      configId: rs.payload.configId,
      status: rs.payload.status,
      phone: rs.payload.phone
    }
    // console.log('[ rs ]', rs)
  }
}

// 获取商家List
const getStoreList = async (): Promise<void> => {
  const rs: any = await getStoreInfos({
    merchantId: Store.state.user.merchantId,
  });
  if (rs.code == 200) {
    storeList.value = rs.payload;
  }
};


// 获取供应商配置
const getConfigList = async()=> {
    if(payConfigList.value.length) {
      return
    }
    let rs: any = await sysConfigApi.getConfigList({externalType: 'supplier'});
    if (rs.code == 200) {
      payConfigList.value = rs.payload
    }
  }

// 保存商家配置
const addSaveOrUpdateStore = async () => {
  console.log('[ 1111 ]', 1111)
  loading.value = true
  let rs: any = await saveOrUpdateStore(ruleForm.form)
  if (rs.code === 200) {
    ElMessage({
      message: `商家配置修改成功`,
      type: 'success',
    })
    confirm()
  }
  loading.value = false

}
const confirm = () => {
  emit("confirm");
  cancel()
};

const cancel = () => {
  setTimeout(() => {
    ruleFormRef.value?.resetFields()
  }, 0);
  emit("cancel", 'showMerchantDialog');
}
const emit = defineEmits(["confirm", "cancel"]);
</script>

<style lang="scss" scoped>
.el-select {
  width: 100%;
}
</style>
